/**
 * Copyright (c) 2010-2011 Pierre Labatut
 *
 * This file is part of Space-Chronicles project.
 *
 * Space-Chronicles is free software: you can redistribute it and/or modify it
 * under the terms of its license which may be found in the accompanying
 * LICENSE file or <http://code.google.com/p/space-chronicles/>.
 */
package space.app.skyview;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.swing.JLabel;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;
import space.app.common.Application;
import space.app.common.ServerFrame;
import space.debug.DbgError;

/**

 * Skyview application. This application is part of the content creation pipeline of space
 * chronicles. It is a skybox lightweight viewer which allows a graphics designer to preview
 * a skybox from a blender scene. It works with a blender plug-in available at
 * http://code.google.com/p/space-chronicles/blender
 *
 * @author Pierre
 */
class SkyViewFrame extends ServerFrame<TextureMessage> {

    final SkyRenderer skyRenderer;

    
    public final Action openAction = new AbstractAction("Open") {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O,
                    InputEvent.CTRL_DOWN_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            final Preferences node = application.preferenceNode();
            final JFileChooser fc = new JFileChooser(node.get("lastDirectory", null));

            fc.setFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    return f.getName().endsWith(".box") || f.isDirectory();
                }

                @Override
                public String getDescription() {
                    return "Skybox Definition (.box)";
                }
            });

            int returnVal = fc.showOpenDialog(SkyViewFrame.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    final URL url = fc.getSelectedFile().toURI().toURL();
                    getStatusLablel().setText("Load "+url);
                    skyRenderer.load(url);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(SkyViewFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            try {
                node.put("lastDirectory", fc.getCurrentDirectory().getCanonicalPath());
                node.flush();
            } catch (BackingStoreException ex) {
                Logger.getLogger(SkyViewFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(SkyViewFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };


    @Override
    public void onServerRecieved(TextureMessage message) {
        super.onServerRecieved(message);
       skyRenderer.updateTexture(message.kind, message.texture);
    }

    
    @Override
    protected List<Image> createImages() {
        return loadImages("skybox-viewer-icon-16.png",
                "skybox-viewer-icon-32.png");
    }

    /**
     * Should be called in swing thread
     */
    public SkyViewFrame(final Application<TextureMessage> application, final URL box) {
        super(application);
        initComponents();

        // Read initial data from preferences &  Setup dialog items
        final int fov;
        final boolean drawbox;
        final boolean headup;

        {
            final Preferences node = Preferences.userNodeForPackage(getClass());
            jShowCubeMenuItem.setSelected(drawbox = node.getBoolean("drawbox", true));
            jHeadUpMenuItem.setSelected(headup = node.getBoolean("headup", true));
            jAllOnTopMenuItem.setSelected(node.getBoolean("alwaysOnTop", false));
            
            
            fov = node.getInt("fov", 90);
        }

        skyRenderer=new SkyRenderer(jJOGLPanel1,drawbox, fov, headup, box);
        skyRenderer.initialize();

    }

   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jStatusPanel = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel4 = new javax.swing.JPanel();
        jStatusLabel = new javax.swing.JLabel();
        jJOGLPanel1 = new space.app.common.JOGLPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jFileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jExitMenu = new javax.swing.JMenuItem();
        jViewMenu = new javax.swing.JMenu();
        jShowCubeMenuItem = new javax.swing.JCheckBoxMenuItem();
        jHeadUpMenuItem = new javax.swing.JCheckBoxMenuItem();
        jAllOnTopMenuItem = new javax.swing.JCheckBoxMenuItem();
        jServerMenu = new javax.swing.JMenu();
        jStartMenu = new javax.swing.JMenuItem();
        jStopMenuItem = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jPrefMenuItem = new javax.swing.JMenuItem();
        jHelpMenu = new javax.swing.JMenu();
        jHelpItem = new javax.swing.JMenuItem();
        jAboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Skybox Viewer");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jStatusPanel.setLayout(new java.awt.BorderLayout());
        jStatusPanel.add(jSeparator1, java.awt.BorderLayout.NORTH);

        jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 2, 4));
        jPanel4.setLayout(new java.awt.BorderLayout());

        jStatusLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/space/app/common/network-offline-16.png"))); // NOI18N
        jStatusLabel.setText("Press then 'Start' button to start listenning, or open a file.");
        jPanel4.add(jStatusLabel, java.awt.BorderLayout.CENTER);

        jStatusPanel.add(jPanel4, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jStatusPanel, java.awt.BorderLayout.SOUTH);
        getContentPane().add(jJOGLPanel1, java.awt.BorderLayout.CENTER);

        jFileMenu.setText("File");

        jMenuItem1.setAction(openAction);
        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Open");
        jFileMenu.add(jMenuItem1);

        jExitMenu.setAction(exitAction);
        jExitMenu.setText("Exit");
        jFileMenu.add(jExitMenu);

        jMenuBar1.add(jFileMenu);

        jViewMenu.setText("View");

        jShowCubeMenuItem.setText("Show Cube");
        jShowCubeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jShowCubeMenuItemActionPerformed(evt);
            }
        });
        jViewMenu.add(jShowCubeMenuItem);

        jHeadUpMenuItem.setText("Head Up");
        jHeadUpMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jHeadUpMenuItemActionPerformed1(evt);
            }
        });
        jViewMenu.add(jHeadUpMenuItem);

        jAllOnTopMenuItem.setAction(allwaysOnTopAction);
        jAllOnTopMenuItem.setText("Always on Top");
        jViewMenu.add(jAllOnTopMenuItem);

        jMenuBar1.add(jViewMenu);

        jServerMenu.setText("Server");

        jStartMenu.setAction(startServerAction);
        jStartMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
        jStartMenu.setText("Start");
        jServerMenu.add(jStartMenu);

        jStopMenuItem.setAction(stopServerAction);
        jStopMenuItem.setText("Stop");
        jServerMenu.add(jStopMenuItem);
        jServerMenu.add(jSeparator3);

        jPrefMenuItem.setAction(showPreferencesAction);
        jPrefMenuItem.setText("Preferences...");
        jServerMenu.add(jPrefMenuItem);

        jMenuBar1.add(jServerMenu);

        jHelpMenu.setText("Help");

        jHelpItem.setAction(showHelpAction);
        jHelpItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jHelpItem.setText("Online Help");
        jHelpMenu.add(jHelpItem);

        jAboutMenuItem.setAction(showAboutAction);
        jAboutMenuItem.setText("About");
        jHelpMenu.add(jAboutMenuItem);

        jMenuBar1.add(jHelpMenu);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        final Preferences node = application.preferenceNode();
        node.putBoolean("drawbox", jShowCubeMenuItem.isSelected());
        node.putBoolean("headup", jHeadUpMenuItem.isSelected());
        node.putBoolean("alwaysOnTop", jAllOnTopMenuItem.isSelected());
        try {
            node.flush();
        } catch (BackingStoreException ex) {
            DbgError.report(ex);
        }
    }//GEN-LAST:event_formWindowClosing

       

    private void jShowCubeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jShowCubeMenuItemActionPerformed
        skyRenderer.updateDrawBox(jShowCubeMenuItem.isSelected());
}//GEN-LAST:event_jShowCubeMenuItemActionPerformed

   
    private void jHeadUpMenuItemActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jHeadUpMenuItemActionPerformed1
        skyRenderer.updateHeadUp(jHeadUpMenuItem.isSelected());
    }//GEN-LAST:event_jHeadUpMenuItemActionPerformed1
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jAboutMenuItem;
    private javax.swing.JCheckBoxMenuItem jAllOnTopMenuItem;
    private javax.swing.JMenuItem jExitMenu;
    private javax.swing.JMenu jFileMenu;
    private javax.swing.JCheckBoxMenuItem jHeadUpMenuItem;
    private javax.swing.JMenuItem jHelpItem;
    private javax.swing.JMenu jHelpMenu;
    private space.app.common.JOGLPanel jJOGLPanel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JMenuItem jPrefMenuItem;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JMenu jServerMenu;
    private javax.swing.JCheckBoxMenuItem jShowCubeMenuItem;
    private javax.swing.JMenuItem jStartMenu;
    private javax.swing.JLabel jStatusLabel;
    private javax.swing.JPanel jStatusPanel;
    private javax.swing.JMenuItem jStopMenuItem;
    private javax.swing.JMenu jViewMenu;
    // End of variables declaration//GEN-END:variables

    @Override
    protected JLabel getStatusLablel() {
        return jStatusLabel;
    }

}
